﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Localization;
using MvcContrib.Pagination;
using SinBiota.Model.Business.PersistenceServices.Interfaces;
using SinBiota.Model.Entities;
using SinBiota.Model.Persistence.Repositories.Interfaces;
using Sinbiota.Web.ActionFilters;
using Sinbiota.Web.Extensions;
using Sinbiota.Web.Models;

namespace Sinbiota.Web.Controllers
{
    [AdminPermission]
    public class LogController : BaseController
    {
        private readonly ILogQueryingServices _logQueryingServices;
        protected static readonly string[] Levels = new[] { "INFO", "DEBUG" };

        public LogController(ILogQueryingServices logQueryingServices)
        {
            _logQueryingServices = logQueryingServices;
        }

        //
        // GET: /Log/
        public ActionResult Index(int? page)
        {
            return View(new LogListModel(_logQueryingServices.FindAll().OrderByDescending(x => x.Date).AsPagination(page ?? 1, 100), AllLevels().ToSelectListItems(x => x.Name, x => x.Id.ToString(), x => x.Id == 0), 0));
        }

        [HttpPost]
        public ActionResult Index(int? page, FormCollection formCollection)
        {
            var selectedLevel = !string.IsNullOrEmpty(formCollection["SelectedLevel"]) ? Convert.ToInt32(formCollection["SelectedLevel"]) : 0;
            // Check if selected level is in the list (otherwise it is the '--Select Level--' line, meaning no level is selected);
            var logs = selectedLevel != 0 ? _logQueryingServices.FindByLevel(Levels[selectedLevel-1]) : _logQueryingServices.FindAll();
            return View(new LogListModel(logs.OrderByDescending(x => x.Date).AsPagination(page ?? 1, 100), AllLevels().ToSelectListItems(x => x.Name, x=> x.Id.ToString(), x => x.Id == selectedLevel), selectedLevel));
        }

        public ActionResult Details(int id)
        {
            var log = _logQueryingServices.FindById(id);
            return log == null ? View("NotFound") : View(log);
        }

        [HttpPost]
        public ActionResult AjaxDetails(int id)
        {
            var log = _logQueryingServices.FindById(id);
            return log == null ? (ActionResult) Content("Details Not Found!") : PartialView("LogDetails", log);
        }

        // Auxiliary classes
        //Loglevel: to create the loglevel select list and easily mantain the user selection using the Id as the <Select> value;
        private static IEnumerable<LogLevel> AllLevels()
        {
            var id = 1;
            return Levels.Select(levelName => new LogLevel(id++,levelName));
        }

    }
    public class LogLevel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public LogLevel(int id, string name)
        {
            Id = id;
            Name = name;
        }
    }
}
